﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.IO;
using Blueprints.Resolution;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Blueprints
{
    /// <summary>
    /// A context within which blueprints can be serialized and deserialized.
    /// </summary>
    public sealed partial class BlueprintContext : DeserializationContext<object>
    {
        /// <summary>
        /// Creates a new BlueprintContext.
        /// </summary>
        /// <param name="targetType">The root type to base the context on. This type is inspected for [TypeResolver] and [BlueprintResolver] attributes.</param>
        public BlueprintContext(Type targetType)
            : base(targetType)
        {
        }

        /// <summary>
        /// Creates a new BlueprintContext.
        /// </summary>
        /// <param name="typeResolver">The type resolver to use within this context.</param>
        /// <param name="blueprintResolver">The blueprint resolver to use within this context.</param>
        public BlueprintContext(ITypeResolver typeResolver, IBlueprintResolver blueprintResolver)
            : base(typeResolver, blueprintResolver)
        {
        }

        // type is provided to enforce deserializing only properties of that type, even if o is a subclass of it
        internal void DeserializePropertiesInternal(Type type, object o, NodeInfoReader reader)
        {
            INode node = reader.Current.Node;

            // If specified, resolve the node's link
            if (!string.IsNullOrEmpty(node.Link))
            {
                if (node.Link.Equals("null") && o == null)
                {
                    return;
                }

                throw new BlueprintDocumentException("Unable to deserialize properties when the root node is a link node", reader.Current.Path);
            }

            // Now that null is ruled out, deserialize to its underlying type when dealing with Nullable<>s.
            TypeInfo actualTypeInfo = type.GetTypeInfo();
            if (actualTypeInfo.IsGenericType
                && actualTypeInfo.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                type = Nullable.GetUnderlyingType(type);
            }

            TypeCategory typeCategory;
            IObjectDescriptor descriptor;
            IReadOnlyList<IPropertyDescriptor> optional;
            try
            {
                typeCategory = TypeResolver.GetTypeCategory(type);
                if (typeCategory != TypeCategory.Object && typeCategory != TypeCategory.NotInstantiable)
                {
                    throw new BlueprintDocumentException("Unable to deserialize properties of a non-object type", reader.Current.Path);
                }

                descriptor = TypeResolver.GetObjectDescriptor(type);
                optional = descriptor.OptionalProperties;
            }
            catch (BlueprintException bex)
            {
                throw new BlueprintDocumentException(bex, reader.Current.Path);
            }

            Dictionary<IPropertyDescriptor, object> optionalValues = new Dictionary<IPropertyDescriptor, object>();
            IEnumerator<INode> subNodes = reader.ReadSubNodes().GetEnumerator();
            while (subNodes.MoveNext())
            {
                IPropertyDescriptor property;
                if (TryMatchProperty(reader, optional, out property))
                {
                    optionalValues[property] = Deserialize(reader, property.Type);
                    continue;
                }

                reader.MoveToEndNode();
            }

            SetObjectProperties(o, optionalValues);
        }

        internal IEnumerable DeserializeItems(NodeInfoReader reader, Type elementType)
        {
            INode node = reader.Current.Node;

            // If specified, resolve the node's link
            if (!string.IsNullOrEmpty(node.Link))
            {
                throw new BlueprintDocumentException("Unable to deserialize items when the root node is a link node", reader.Current.Path);
            }

            IEnumerator<INode> subNodes = reader.ReadSubNodes().GetEnumerator();
            while (subNodes.MoveNext())
            {
                yield return Deserialize(reader, elementType);
            }
        }
    }
}